package com.labbit.platform.manager.service.impl;

import com.labbit.platform.commons.constants.RedisKeys;
import com.labbit.platform.commons.properties.CommonProperties;
import com.labbit.platform.commons.session.SessionData;
import com.labbit.platform.commons.session.SessionUtils;
import com.labbit.platform.commons.utils.IdGen;
import com.labbit.platform.commons.utils.joda.JodaUtil;
import com.labbit.platform.manager.dao.MiniUserMapper;
import com.labbit.platform.manager.domain.po.MiniUser;
import com.labbit.platform.manager.exception.LoginException;
import com.labbit.platform.manager.exception.message.UserError;
import com.labbit.platform.manager.service.MobileMessageService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @description:
 * @Author: CHEN YU
 * @Date: 2020-12-29 19:50
 **/
@Service
@Slf4j
public class MobileMessageServiceImpl implements MobileMessageService {

    @Resource
    private RedisTemplate<String, Integer> redisTemplate;

    @Autowired
    private CommonProperties commonProperties;

    @Autowired
    private MiniUserMapper miniUserMapper;

    @Override
    public void sendMiniLoginMessage(String phone) {
        // 1. 生成code
        Integer code = RandomUtils.nextInt(100000,999999);
        log.debug("手机号[{}]发送登录验证码, 验证码：[{}]", phone, code);
        // 2. 调用第三方发送验证码

        // 3. 存入到redis
        redisTemplate.opsForValue().set(RedisKeys.PHONE_VALID_MESSAGE_PREFIX + phone, code, commonProperties.getPhoneValidMessageTime(), TimeUnit.MINUTES);
    }

    @Override
    public SessionData loginValidAndRegister(String phone, Integer validCode) {
        Integer codeFromRedis = redisTemplate.opsForValue().get(RedisKeys.PHONE_VALID_MESSAGE_PREFIX + phone);
        if (!validCode.equals(codeFromRedis)) {
            throw new LoginException(UserError.MESSAGE_CODE_INVALID);
        }
        // 从Redis删除验证码
        redisTemplate.delete(RedisKeys.PHONE_VALID_MESSAGE_PREFIX + phone);
        // 查询UserId
        String userId = miniUserMapper.selectUserIdByPhone(phone);
        if(StringUtils.isEmpty(userId)) {
            // 创建用户信息
            MiniUser miniUser = new MiniUser();
            miniUser.setId(IdGen.getId());
            miniUser.setCreatedDate(JodaUtil.getNowDate());
            miniUser.setPhone(phone);
            userId = miniUser.getId();
        }
        SessionData sessionData = new SessionData();
        sessionData.setId(userId);
        sessionData.setPhone(phone);
        sessionData.setToken(UUID.randomUUID().toString());

        SessionUtils.putSession(sessionData.getToken(), sessionData);

        return sessionData;
    }
}
